package com.pigs.pigsordersystem.interceptor;

import com.alibaba.fastjson.JSON;
import com.pigs.pigsordersystem.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 如果都没有那就返回 客户端 账户 或密码有错！的超友好提示
 * 拦截器
 *
 * @author PIGS
 */
@Component
public class UserLoginInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(UserLoginInterceptor.class);


    /**
     * 判断session 是否有值
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userName = (String) request.getSession().getAttribute("userName");
        logger.info("userName={}",userName);
        if (userName==null){
            String result = JSON.toJSONString(ResultUtil.error(101, "你还没有登录哦！"));
            returnJson(response, result);
            return false;
        }


        return true;
    }

    /**
     * 返回客户端数据
     */
    private void returnJson(HttpServletResponse response, String result) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(result);

        } catch (IOException e) {
        } finally {
            if (writer != null) {
                writer.close();
            }
        }

    }


    /**
     * 处理请求完成后视图渲染之前的处理操作
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object
            o, ModelAndView modelAndView) throws Exception {

    }


    /**
     * 视图渲染之后的操作
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse
            httpServletResponse, Object o, Exception e) throws Exception {

    }


}
